
/* -----------------
* brief 
* 1. this is code gen by tools 
* 2. for add/update/delete/query the data save in sql database   
*/

package system

import (
	"fmt"
	"github.com/go-xorm/xorm"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
)


/* 根据账号密码获取用户以验证登陆
 * -----------------
 */
func (t *SysUser) EncryptPassword(password string) string {
	prefix := "#YHUHUaaaasd7823*#"
	subfix := "#9jhuasdf2qasdfgy*#"
	ptx := fmt.Sprintf("%s-%s-%s", prefix, password, subfix)
	return utils.Md5(ptx)
}


/* 根据id获取记录
 * -----------------
 */
func (t *SysUser) RecodeByAccount(account string) *SysUser {
	item := new(SysUser)
	_, err := lego.GetDBEngine().Where("account=?",account).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}
	return item
}

/* 根据id获取记录
 * -----------------
 */
func (t *SysUser) RecodeById(id int64) *SysUser {
	item := new(SysUser)
	_, err := lego.GetDBEngine().ID(id).Get(item)
	if err != nil || item.Id <= 0 {
		return nil
	}
	return item
}

/* 添加
 * -----------------
 */
func (t *SysUser) AddRecode(item2add *SysUser,profile *SysUserProfile) bool {
	_,err := lego.GetDBEngine().Transaction(func(session *xorm.Session) (interface{}, error) {
		item2add.Id = lego.UUID()
		_, err := session.Insert(item2add)
		if err != nil {
			lego.LogError(err)
			return nil ,err
		}

		profile.Id = lego.UUID()
		profile.SysUid = item2add.Id
		_, err = session.Insert(profile)
		if err != nil {
			lego.LogError(err)
			return nil ,err
		}
		return nil,nil
	})
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}

/* 删除(硬删除)*/
func (t *SysUser) DelRecodeById(id int64) bool {
	item := new(SysUser)
	_, err := lego.GetDBEngine().ID(id).Delete(item)
	if err != nil {
        lego.LogError(err)
        return false
    }
    return true
}

/* 更新
 * -----------------*/
func (t *SysUser) UpdateRecode(rc *SysUser,profile *SysUserProfile,profileExit bool) bool {
	_,err := lego.GetDBEngine().Transaction(func(session *xorm.Session) (interface{}, error) {
		_, err := session.ID(rc.Id).Update(rc)
		if err != nil {
			lego.LogError(err)
			return nil,err
		}

		if profileExit {
			_,errin := session.Table(profile).Where("sys_uid=?",rc.Id).Update(profile)
			if errin != nil {
				session.Rollback()
				return 0,errin
			}
		}else{
			profile.Id = lego.UUID()
			profile.SysUid = rc.Id
			_, err = session.Insert(profile)
			if err != nil {
				lego.LogError(err)
				return nil ,err
			}
		}
		return nil,nil
	})
	if err != nil {
		lego.LogError(err)
		return false
	}
	return true
}